package cc.toprank.syncdatatask;

import cc.toprank.syncdatatask.canal.CanalClient;
import cc.toprank.syncdatatask.pojo.Merchant;
import cc.toprank.syncdatatask.pojo.Organization;
import cc.toprank.syncdatatask.pojo.RshHandler;
import cc.toprank.syncdatatask.util.GlobalContants;
import com.toprank.druid.store.jdbc.SqlTemplate;
import com.toprank.druid.store.jdbc.builder.SelectSql;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@SpringBootApplication
public class ClientApplication {
	private Logger logger = Logger.getLogger(ClientApplication.class);
	@Autowired
	SqlTemplate sqlTemplate;
	public static void main(String[] args) {
		SpringApplication.run(ClientApplication.class, args);
	}
	@Autowired
	public void run(RabbitTemplate rabbitTemplate,
					CanalClient clusterCanalClient ) throws Exception {
		Merchant merchant = selectClientInfo();
		if (null != merchant) {
			GlobalContants.ARCHIVE_ID = merchant.getArchiveID();
			GlobalContants.ORG_ID.add(String.valueOf(merchant.getOrgID()));
			logger.info("正确获取商家档案ID:" + merchant.toString());

			initOrganization(String.valueOf(merchant.getOrgID()));
		}
		clusterCanalClient.startCanal(rabbitTemplate);
		logger.debug("服务端初始化canal和消息监听器成功");
	}

	/**
	 * 只初始化b_merchantinfo org_id 的子类
	 * @param orgID
	 */
	private void initOrganization(String orgID){
		List<Organization> list  =  selectOrganization(orgID);
		for(Organization organization : list){
			GlobalContants.ORG_ID.add(String.valueOf(organization.getOrgID()));
			if(null != organization && 0 != organization.getOrgID()){
				initOrganization(String.valueOf(organization.getOrgID()));
			}
			//GlobalContants.ORG_ID.add(String.valueOf(organization.getParentID()));
		}
	}


	public Merchant selectClientInfo() {
		SelectSql selectSql = new SelectSql(sqlTemplate);
		return selectSql.select()
				.columns("ArchiveID,OrgID")
				.from()
				.table("B_MerchantInfo").single(RshHandler.Merchant_RSH);
	}

	public List<Organization> selectOrganization(String orgID) {
		SelectSql selectSql = new SelectSql(sqlTemplate);
		return selectSql.select()
				.columns("ParentID,OrgID")
				.from()
				.table("U_OrganizationInfo")
				.where("ParentID = ?", orgID)
				.list(RshHandler.Organization_LIST_RSH);
	}
}
